﻿app.controller('ICDDicDataCtrl', function ($scope, $modal, $log, $rootScope, $interval, $timeout, $stateParams, $element, tabService, icdDicData) {
    $scope.treeData = [];
    $scope.myTree = tree = {};
    $scope.myTable = {};
    $scope.myMappingTable = {};
    $scope.key = $stateParams.key;
    $scope.type = $stateParams.type;
    $scope.TreeName = $scope.type;
    var selectedMostLeafNode = false;
    var topData;
    $scope.noSelectSync = false;
    var tablePanel = angular.element("#" + "myMenu" + tabService.getTabByMenuID().id).find('.tablePanel');
    $scope.isSelectBottom = false;

    var selectTalbeRowByTreeNode = function () {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        var api = curScope.myTable.api();

        if (!curScope.dicDataTreeSelection) {
            return;
        }
        //如果选中的节点下有子节点，取消table中的选中
        if (curScope.dicDataTreeSelection.children && curScope.dicDataTreeSelection.children.length > 0) {
            if (api.rows().nodes().length > 0) {
                api.rows('.selected').nodes().to$().removeClass('selected');
            }
            return;
        }

        var datas = api.rows().data();
        if (curScope.dicDataTreeSelection && curScope.dtData && curScope.dtData.length > 0 && datas && datas.length > 0 && curScope.dtData.length == datas.length) {
            for (var i = 0; i < datas.length; i++) {
                if (datas[i].SerialNo == curScope.dicDataTreeSelection.data.SerialNo) {
                    var pageIndex = api.page();
                    var pageLength = api.page.len();
                    row = api.row(function (idx, data, node) {
                        return data.SerialNo == curScope.dicDataTreeSelection.data.SerialNo ? true : false;
                    }).node();
                    //tree上选中的节点项目不在table当前页时，table自动翻页
                    if (i < pageIndex * pageLength || i > (pageIndex + 1) * pageLength - 1) {
                        api.page(parseInt(i / pageLength)).draw(false);
                        //api.page(Math.floor(i / pageLength)).draw(false);
                    }
                    selectTableRow(angular.element(row), datas[i]);
                    break;
                }
            }
        }
    };

    var CollapseTreeNode = function (branch, clickedBranch) {
        //如果当前循环到的节点是底层节点就跳出
        if (!branch.children || (branch.children && branch.children.length == 0)) {
            return true;
        }
        if (parentBranches.indexOf(branch) < 0 && branch.expanded == true) {
            var selectedTab = tabService.getTabByMenuID();
            var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
            curScope.myTree.collapse_branch(branch);
        }
        if (branch.children && branch.children.length > 0) {
            for (var i = 0; i < branch.children.length; i++) {
                if (CollapseTreeNode(branch.children[i])) {
                    break;
                }
            }
        }
    }

    var parentBranches = new Array();

    var AddParentBranchToArray = function (branch) {
        parentBranches.push(branch);
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        var parentBranch = curScope.myTree.get_parent_branch(branch);
        if (parentBranch) {
            AddParentBranchToArray(parentBranch);
        } else {
            return;
        }
    }

    var CollapseOtherTreeNodes = function (clickedBranch) {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        if (!clickedBranch.expanded) {
            curScope.myTree.expand_branch(clickedBranch);
        }
        parentBranches.length = 0;
        AddParentBranchToArray(clickedBranch);
        //选中节点的父级节点及以上的父级节点展开状态不变，其他节点全部折叠
        for (var i = 0; i < curScope.treeData.length; i++) {
            CollapseTreeNode(curScope.treeData[i], clickedBranch);
        }
    }

    $scope.treeSelectHandler = function (branch) {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        //var selectedBranch = curScope.dicDataTreeSelection = curScope.myTree.get_selected_branch();
        curScope.dicDataTreeSelection = branch;

        if (branch.data) {
            if (branch.data.IsBottom) {
                if (tablePanel.hasClass('right-content-body')) {
                    tablePanel.removeClass('right-content-body');
                }
                curScope.isSelectBottom = true;
                if (curScope.type == 'ICD-10') {
                    getSynonym(branch.data.Code);
                    getMapping(branch.data.Code);
                } else {
                    curScope.myTable.api().clear().draw();
                }
            } else {
                if (!tablePanel.hasClass('right-content-body')) {
                    tablePanel.addClass('right-content-body');
                }
                curScope.isSelectBottom = false;
                curScope.synonymInfo = '';
                //curScope.dtMappingData = '{}';
                getByParent(branch.data.Code);
                CollapseOtherTreeNodes(branch);
                ////如果选中树中的顶级节点，且此节点下没有子节点，清空table
                //if ((!branch.children || (branch.children && branch.children.length == 0)) && branch.data.ParentKey == topData.Key) {
                //    curScope.dtData = null;
                //    curScope.myTable.api().clear().draw();
                //    return;
                //}

                //var nodes = branch.data.ChildNodes;
                //if (nodes != null && nodes.length > 0) {
                //    selectedMostLeafNode = false;
                //    selected.length = 0;
                //} else {
                //    nodes = curScope.myTree.get_parent_branch(branch).data.ChildNodes;
                //    selectedMostLeafNode = true;
                //}
                //if (curScope.dtData !== nodes) {
                //    curScope.dtData = nodes;
                //}
                selectTalbeRowByTreeNode();
            }
        } else {
            curScope.myTable.api().clear().draw();
        }
    };

    var TreeDataFormat = function (item) {
        var data;
        if (item.IsBottom) {
            data = {
                label: item.Code + ' ' + item.Value,
                data: item
            }
        } else {
            data = {
                label: item.Code + ' ' + item.Value,
                data: item,
                children: [{
                    label: '加载中...',
                    data: null
                    //ParentCode: null,
                    //LevelCode: null,
                    //LevelName: null,
                    //RelationCode: null,
                    //IsBottom: false,
                    //Key: null,
                    //Code: null,
                    //Value: '加载中...',
                    //EnglishName: null,
                    //Description: null,
                    //InputCode: null,
                    //AbbInfo: {
                    //    Code: null,
                    //    Name: null
                    //},
                    //StatusCode: null,
                    //FromMethod: null,
                    //SerialNo: null
                }]
            }
        }

        //if (item.ChildNodes && item.ChildNodes.length > 0) {
        //    data = {
        //        label: item.Code + ' ' + item.Value,
        //        data: item,
        //        children: []
        //    }
        //} else {
        //    data = {
        //        label: item.Code + ' ' + item.Value,
        //        data: item
        //    }
        //}
        return data;
    }

    var MakeTreeData = function (item) {
        var a = TreeDataFormat(item);
        if (item.ChildNodes && item.ChildNodes.length > 0) {
            for (var i = 0; i < item.ChildNodes.length; i++) {
                a.children.push(MakeTreeData(item.ChildNodes[i]));
            }
        }
        return a;
    }

    var getBranchByParentAndCode = function (parent, code) {
        if (parent.data) {
            if (parent.data.Code == code) {
                return parent;
            } else {
                if (parent.children && parent.children.length > 0) {
                    for (var i = 0; i < parent.children.length; i++) {
                        var b = getBranchByParentAndCode(parent.children[i], code);
                        if (b) {
                            return b;
                        }
                    }
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    }

    var getBranchByCode = function (code) {
        var branch;
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        for (var i = 0; i < curScope.treeData.length; i++) {
            branch = getBranchByParentAndCode(curScope.treeData[i], code);
            if (branch) {
                return branch;
            }
        }
        return branch;
    }

    var getBranchByParentAndKey = function (parent, key) {
        if (parent.data) {
            if (parent.data.Key == key) {
                return parent;
            } else {
                if (parent.children && parent.children.length > 0) {
                    for (var i = 0; i < parent.children.length; i++) {
                        var b = getBranchByParentAndKey(parent.children[i], key);
                        if (b) {
                            return b;
                        }
                    }
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    };

    var getBranchByKey = function (key) {
        var branch;
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        for (var i = 0; i < curScope.treeData.length; i++) {
            branch = getBranchByParentAndKey(curScope.treeData[i], key);
            if (branch) {
                return branch;
            }
        }
        return branch;
    };

    var getBranchByParentAndSerialNo = function (parent, sn) {
        if (parent.data) {
            if (parent.data.SerialNo == sn) {
                return parent;
            } else {
                if (parent.children && parent.children.length > 0) {
                    for (var i = 0; i < parent.children.length; i++) {
                        var b = getBranchByParentAndSerialNo(parent.children[i], sn);
                        if (b) {
                            return b;
                        }
                    }
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    };

    var getBranchBySerialNo = function (sn) {
        var branch;
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        for (var i = 0; i < curScope.treeData.length; i++) {
            branch = getBranchByParentAndSerialNo(curScope.treeData[i], sn);
            if (branch) {
                return branch;
            }
        }
        return branch;
    };

    var getByParent = function (pcode, initData) {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        //如果有就跳出（不跳出，重新加载），没有就获取
        icdDicData.GetByParent(pcode, curScope.type).success(function (data, header, config, status) {
            if (data == null) {
                return;
            }
            if (data.length == 0) {
                curScope.myTable.api().clear().draw();
                return;
            }
            var isGettingChildren = false;
            if (curScope.treeData && curScope.treeData.length > 0) {
                isGettingChildren = true;
            }
            var d;
            if (!isGettingChildren) {
                var da = {
                    //Value: 'ICD-10',
                    ChildNodes: data
                }
                //curScope.TreeName = da.Value;
                topData = da;
                d = da.ChildNodes;
            } else {
                var d = data;
            }
            var dd = new Array();
            for (var i = 0; i < d.length; i++) {
                var o = d[i];
                var item = MakeTreeData(o, null);
                dd.push(item);
            }
            if (curScope.treeData && curScope.treeData.length > 0) {
                var dc = getBranchByCode(pcode);
                dc.children = dd;
            } else {
                curScope.treeData = dd;
            }
            curScope.dtData = d;
            //if (initData) {
            //    var sel;
            //    for (var i = 0; i < curScope.treeData.length; i++) {
            //        sel = getBranchByParentAndSerialNo(curScope.treeData[i], initData.SerialNo);
            //        if (sel) {
            //            curScope.myTree.expand_branch(sel);
            //            var parentKey = sel.data.ParentKey;
            //            while (parentKey) {
            //                for (var j = 0; j < curScope.treeData.length; j++) {
            //                    var parent = getBranchByParentAndKey(curScope.treeData[i], parentKey);
            //                    if (parent) {
            //                        curScope.myTree.expand_branch(parent);
            //                        parentKey = parent.data.ParentKey;
            //                    } else {
            //                        parentKey = false;
            //                    }
            //                    break;
            //                }
            //            }
            //            curScope.myTree.select_branch(sel);
            //            break;
            //        }
            //    }
            //} else {
            //    if (curScope.treeData.length > 0) {
            //        var branch = curScope.treeData[0];
            //        var pBranch = branch;
            //        curScope.myTree.expand_branch(pBranch);
            //        while (branch.children && branch.children.length > 0) {
            //            pBranch = branch;
            //            curScope.myTree.expand_branch(pBranch);
            //            branch = branch.children[0];
            //        }
            //        curScope.myTree.expand_branch(pBranch);
            //        curScope.myTree.select_branch(pBranch);
            //    }
            //}
        }).error(function (data, header, config, status) {
            //处理响应失败
            angular.alert('API接口响应错误！');
        }).finally(function () {
            //hideThead();
        });
    }

    var getSynonym = function (scode) {
        icdDicData.GetSynonym(scode).success(function (data, header, config, status) {
            if (data == null) {
                return;
            }
            var selectedTab = tabService.getTabByMenuID();
            var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
            if (data.length == 0) {
                curScope.synonymInfo = '';
                return;
            }

            var synonym = '';
            for (var i = 0; i < data.length; i++) {
                if (i == data.length - 1) {
                    synonym += data[i].Value;
                } else {
                    synonym += data[i].Value + '；';
                }
            }
            curScope.synonymInfo = synonym;
        }).error(function (data, header, config, status) {
            //处理响应失败
            angular.alert('API接口响应错误！');
        }).finally(function () {
            //hideThead();
        });
    }

    var getMapping = function (mcode) {
        icdDicData.GetMapping(mcode).success(function (data, header, config, status) {
            if (data == null) {
                return;
            }
            var selectedTab = tabService.getTabByMenuID();
            var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
            if (data.length == 0) {
                curScope.myMappingTable.api().clear().draw();
                return;
            }

            curScope.dtMappingData = data;
        }).error(function (data, header, config, status) {
            //处理响应失败
            angular.alert('API接口响应错误！');
        }).finally(function () {
            //hideThead();
        });
    }

    var init = function (initData) {
        if ($scope.key != null) {
            getByParent(0, initData);
            //icdDicData.GetByParent($scope.key).success(function (data, header, config, status) {
            //    if (data == null) {
            //        return;
            //    }
            //    var selectedTab = tabService.getTabByMenuID();
            //    var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
            //    curScope.TreeName = data.Value;
            //    topData = data;
            //    var dd = new Array();
            //    var d = data.ChildNodes;
            //    for (var i = 0; i < d.length; i++) {
            //        var o = d[i];
            //        var item = MakeTreeData(o, null);
            //        dd.push(item);
            //    }
            //    curScope.treeData = dd;
            //    if (initData) {
            //        var sel;
            //        for (var i = 0; i < curScope.treeData.length; i++) {
            //            sel = getBranchByParentAndSerialNo(curScope.treeData[i], initData.SerialNo);
            //            if (sel) {
            //                curScope.myTree.expand_branch(sel);
            //                var parentKey = sel.data.ParentKey;
            //                while (parentKey) {
            //                    for (var j = 0; j < curScope.treeData.length; j++) {
            //                        var parent = getBranchByParentAndKey(curScope.treeData[i], parentKey);
            //                        if (parent) {
            //                            curScope.myTree.expand_branch(parent);
            //                            parentKey = parent.data.ParentKey;
            //                        } else {
            //                            parentKey = false;
            //                        }
            //                        break;
            //                    }
            //                }
            //                curScope.myTree.select_branch(sel);
            //                break;
            //            }
            //        }
            //    } else {
            //        if (curScope.treeData.length > 0) {
            //            var branch = curScope.treeData[0];
            //            var pBranch = branch;
            //            curScope.myTree.expand_branch(pBranch);
            //            while (branch.children && branch.children.length > 0) {
            //                pBranch = branch;
            //                curScope.myTree.expand_branch(pBranch);
            //                branch = branch.children[0];
            //            }
            //            curScope.myTree.expand_branch(pBranch);
            //            curScope.myTree.select_branch(pBranch);
            //        }
            //    }
            //}).error(function (data, header, config, status) {
            //    //处理响应失败
            //    angular.alert('API接口响应错误！');
            //}).finally(function () {
            //    hideThead();
            //});
        }
    };

    function hideThead() {
        $timeout(function () {
            var selectedTab = tabService.getTabByMenuID();
            var contentElement = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement");
            setAutoTableHeight(contentElement);
        }, 500)

        //var timeMethod = $interval(function () {
        //    var selectedTab = tabService.getTabByMenuID();
        //    var contentElement = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement");
        //    setAutoTableHeight(contentElement);
        //    setSplitterLeft(contentElement, selectedTab);
        //}, 1000);
        //$scope.$on('$destroy', function () {
        //    $interval.cancel(timeMethod);
        //});        
    }

    init();

    $scope.reloadTree = function () {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        curScope.treeData = null;
        curScope.dicDataTreeSelection = null;
        curScope.isSelectBottom = false;
        if (tablePanel.hasClass('right-content-body')) {
            tablePanel.removeClass('right-content-body');
        }
        //curScope.myTable.api().clear().draw();
        init();
    };

    var selected = new Array();
    var dtOrder;
    $scope.open = function (type, size) {
        if (type == 'edit' && (selected.length > 1 || selected.length == 0)) {
            angular.alert('请选中一个底层项目进行编辑');
            return;
        }
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        var api = curScope.myTable.api();
        dtOrder = api.order();
        var modalInstance = $modal.open({
            templateUrl: 'template/dictsystematictreeadd.html',
            controller: 'DicDataAddCtrl',
            size: 'lg',
            backdrop: 'static',
            resolve: {
                type: function () {
                    return type;
                },
                selected: function () {
                    return selected;
                },
                selectedBranch: function () {
                    return curScope.myTree.get_selected_branch();
                },
                parentBranch: function () {
                    var selectedBranch = curScope.myTree.get_selected_branch();
                    return selectedMostLeafNode ? curScope.myTree.get_parent_branch(selectedBranch) : selectedBranch;
                },
                topData: function () {
                    return topData;
                },
                deps: ['$ocLazyLoad',
                    function ($ocLazyLoad) {
                        return $ocLazyLoad.load(['js/controllers/dictsystematictreeadd.js']);
                    }]
            }
        });

        modalInstance.result.then(function (item) {
            switch (type) {
                case 'edit':
                    icdDicData.Edit(item).success(function (data, header, config, status) {
                        //dtReload();
                        //treeReload(OperationMode.Edit, item);
                        init(item);
                    }).error(function (data, header, config, status) {
                        angular.alert('API接口响应错误！');
                    });
                    break;
                default:
                    icdDicData.Add(item).success(function (data, header, config, status) {
                        //item.SerialNo = data;
                        //treeReload(OperationMode.Add, item);
                        //dtReload(OperationMode.Add, item);
                        //if (!tree.get_selected_branch().expanded) {
                        //    tree.expand_branch();
                        //}
                        var selectedTab = tabService.getTabByMenuID();
                        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
                        if (curScope.dicDataTreeSelection) {
                            init(curScope.dicDataTreeSelection.data);
                            if (dtOrder) {
                                curScope.myTable.api().order(dtOrder).draw();
                                dtOrder = null;
                            }
                        } else {
                            init();
                        }
                    }).error(function (data, header, config, status) {
                        angular.alert('API接口响应错误！');
                    });
                    break;
            }
            $log.info('OK at: ' + new Date());
        }, function (item) {
            if (item) {
                var selectedTab = tabService.getTabByMenuID();
                var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
                if (curScope.dicDataTreeSelection) {
                    init(curScope.dicDataTreeSelection.data);
                } else {
                    init(getBranchBySerialNo(item.SerialNo));
                }
            }
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    if (typeof OperationMode == 'undefined') {
        var OperationMode = {
            Search: 0,
            Add: 1,
            Edit: 2,
            Delete: 3
        }
    }

    var dtReload = function (operationMode, item) {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        var existing = curScope.dtData.slice();
        switch (operationMode) {
            case OperationMode.Add:
                if (item) {
                    existing.push(item);
                }
                break;
            case OperationMode.Delete:
                if (item) {
                    existing.splice($.inArray(item, existing), 1);
                }
                break;
            default:
                break;
        }
        if (existing.length == 0) {
            curScope.dtData = '{}';
        } else {
            curScope.dtData = existing;
        }
    };

    var treeReloadByParent = function (item, parent, operation) {
        if (parent.data.Key == item.data.ParentKey) {
            switch (operation) {
                case OperationMode.Add:
                    parent.children.push(item);
                    parent.data.ChildNodes.push(item.data);
                    return true;
                    break;
                case OperationMode.Delete:
                    for (var i = 0; i < parent.children.length; i++) {
                        if (parent.children[i].data.Key == item.data.Key) {
                            parent.children.splice(i, 1);
                            return true;
                        }
                    }
                    break;
                case OperationMode.Edit:
                    for (var i = 0; i < parent.children.length; i++) {
                        if (parent.children[i].data.Key == item.data.Key) {
                            parent.children[i].label = item.label;
                            parent.children[i].data = item.data;
                            return true;
                        }
                    }
                    break;
            }
        } else {
            if (parent.children && parent.children.length > 0) {
                for (var i = 0; i < parent.children.length; i++) {
                    if (treeReloadByParent(item, parent.children[i], operation)) {
                        return true;
                    }
                }
            }
        }
    }

    var treeReload = function (operationMode, item) {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        var existing = curScope.treeData.slice();
        if (item && (operationMode == OperationMode.Add || operationMode == OperationMode.Delete || operationMode == OperationMode.Edit)) {
            for (var i = 0; i < existing.length; i++) {
                if (treeReloadByParent(TreeDataFormat(item), existing[i], operationMode)) {
                    break;
                }
            }
        }
        curScope.treeData = existing;
    };

    $scope.remove = function () {
        if (selected.length == 0) {
            angular.alert('请选中项目后再删除！');
            return;
        }
        if (selected[0].ChildNodes && selected[0].ChildNodes.length > 0) {
            angular.alert('节点下有子节点，请删除子节点后再删除此节点！');
            return;
        }
        angular.alert('确定删除选中的项目吗？', null, true).ok(function () {
            var selectedTab = tabService.getTabByMenuID();
            var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
            var pBranch = curScope.myTree.get_parent_branch(curScope.dicDataTreeSelection);
            icdDicData.Delete(selected[0].SerialNo).success(function (data, header, config, status) {
                //dtReload(OperationMode.Delete, selected[0]);
                //treeReload(OperationMode.Delete, selected[0]);
                //alert('success');
                init(pBranch.data);
            }).error(function (data, header, config, status) {
                angular.alert('删除失败！');
            });
        }).cancel(function () { });
    }

    $scope.rowCallback = function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        angular.element(nRow).unbind('click');
        angular.element(nRow).bind('click', function () {
            var selectedTab = tabService.getTabByMenuID();
            var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
            curScope.someClickHandler(angular.element(nRow), aData);
        });
        return nRow;
    };

    var selectTableRow = function (row, info) {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        var api = curScope.myTable.api();
        if (!row) {
            row = api.row(function (idx, data, node) {
                return data.SerialNo == curScope.dicDataTreeSelection.data.SerialNo ? true : false;
            }).nodes().to$();
        }
        if (!info) {
            api.row(function (idx, data, node) {
                if (data.SerialNo == curScope.dicDataTreeSelection.data.SerialNo) {
                    info = data;
                    return true;
                }
            });
        }
        var selectedRow = api.rows('.selected');

        var data = selectedRow.data();
        if (data.length == 0) {
            row.addClass('selected');
        } else if (info.SerialNo != data[0].SerialNo) {
            selectedRow.nodes().to$().removeClass('selected');
            row.addClass('selected');
        }

        selected.length = 0;
        selected.push(info);
    };

    $scope.someClickHandler = function (row, info) {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        //选中table中的项时，自动选中tree中对应的节点
        var branch = getBranchBySerialNo(info.SerialNo);
        if (branch) {
            curScope.myTree.select_branch(branch);
            //如果table中选中的项在tree上有子节点，则展开此节点
            if (branch.children && branch.children.length > 0) {
                curScope.myTree.expand_branch(branch);
            }
        }
        selectTableRow(row, info);
    };

    $scope.columnDefs = [
        { data: 'SerialNo', searchable: false, orderable: false, title: '序号', type: 'num', visible: true,/* width: '10%',*/ targets: 0 },
        { data: 'Code', targets: 1 },
        { data: 'Value', targets: 2 }
    ];

    $scope.mappingColumnDefs = [
        { data: 'SerialNo', searchable: false, orderable: false, title: '序号', type: 'num', visible: true,/* width: '10%',*/ targets: 0 },
        { data: 'VersionName', targets: 1 },
        { data: 'Code', targets: 2 },
        { data: 'Value', targets: 3 }
    ];

    $scope.dtOptions = {
        //order: [[0, 'desc']],
        info: true,
        ordering: true,
        paging: true,
        processing: false,
        searching: true,
        scrollY: '100px',
        autoWidth: false,
        stateSave: false,
        stateDuration: 60 * 60 * 24,
        lengthMenu: [14, 50, 100],
        pagingType: 'full_numbers',
        search: {
            caseInsensitive: false,
            regex: true,
            smart: false
        },
        language: {
            url: 'vendor/jquery/datatables/Chinese.json'
        },
        drawCallback: function (settings) {
            var selectedTab = tabService.getTabByMenuID();
            var contentElement = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement");
            setAutoTableHeadClass(contentElement);

            var curScope = contentElement.scope();
            this.api().column(0).nodes().each(function (cell, i) {
                cell.innerHTML = i + 1;
            });
            if (!curScope.noSelectSync) {
                selectTalbeRowByTreeNode();
            } else {
                selectTableRow();
            }
            curScope.noSelectSync = false;
        }
    };

    $scope.dtMappingOptions = {
        //order: [[0, 'desc']],
        info: false,
        ordering: false,
        paging: false,
        processing: false,
        searching: false,
        scrollY: '100px',
        autoWidth: false,
        stateSave: false,
        stateDuration: 60 * 60 * 24,
        //lengthMenu: [14, 50, 100],
        //pagingType: 'full_numbers',
        //search: {
        //    caseInsensitive: false,
        //    regex: true,
        //    smart: false
        //},
        language: {
            url: 'vendor/jquery/datatables/Chinese.json'
        },
        drawCallback: function (settings) {
            var selectedTab = tabService.getTabByMenuID();
            var contentElement = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement");
            setAutoTableHeadClass(contentElement);

            var curScope = contentElement.scope();
            this.api().column(0).nodes().each(function (cell, i) {
                cell.innerHTML = i + 1;
            });
            //if (!curScope.noSelectSync) {
            //    selectTalbeRowByTreeNode();
            //} else {
            //    selectTableRow();
            //}
            //curScope.noSelectSync = false;
        }
    };

    $('.tableDictsystematictree1').on('page.dt', function () {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        curScope.noSelectSync = true;
    });

    var mappingSelected = new Array();
    $scope.mappingRowCallback = function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        var row = angular.element(nRow);
        row.unbind('click');
        row.bind('click', function () {
            var selectedTab = tabService.getTabByMenuID();
            var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
            var api = curScope.myMappingTable.api();
            var selectedRow = api.rows('.selected');

            var data = selectedRow.data();
            
            if (data.length == 0) {
                row.addClass('selected');
            } else if (aData.SerialNo != data[0].SerialNo) {
                selectedRow.nodes().to$().removeClass('selected');
                row.addClass('selected');
            }

            mappingSelected.length = 0;
            mappingSelected.push(aData);
        });
        return nRow;
    };
});
